from time import sleep
import os, sys
try:
    from PyQt5.QtCore import QRegExp,Qt
    from PyQt5.QtWidgets import QPushButton, QTextEdit, QWidget, QApplication, QVBoxLayout, QComboBox, QCheckBox, QHBoxLayout
    import pyautogui
    import win32gui
except:
    os.system("pip3 install pywin32 pyautogui pyqt5")
    sys.exit(0)
import ctypes
if ctypes.windll.kernel32.GetConsoleWindow() !=0:
    ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(),0)
    ctypes.windll.kernel32.CloseHandle(ctypes.windll.kernel32.GetConsoleWindow(),0)


global windowsL
windowsL =[]
def winEnumHandler( hwnd, ctx ):
    global windowsL
    if win32gui.IsWindowVisible(hwnd):
        windowsL.append( (hwnd, win32gui.GetWindowText(hwnd) ))
    
def windowsList():
    global windowsL
    windowsL =[]
    win32gui.EnumWindows(winEnumHandler, None)
    v1=[]
    v2=[]
    for i in windowsL:
        if i[1]!='':
            v1.append(i[0])
            v2.append(i[1])
    windowsL= [v1, v2]
        

class Win(QWidget):
    def __init__(self):
        global windowsL
        super().__init__()
        self.setGeometry(200, 200, 400, 400)
        self.setWindowTitle('Tools')
        self.text1 = QTextEdit()
        self.cb= QComboBox()
        self.btn2 = QPushButton('刷新窗口')
        self.c= QCheckBox('慢速输入')
        self.cb.addItems(windowsL[1])
        self.btn1 = QPushButton('开始输入')
        layout = QVBoxLayout()
        layout1= QHBoxLayout()
        layout.addStretch(1)
        layout.addWidget(self.text1)
        layout.addWidget(self.cb)
        
        layout1.addWidget(self.c)
        layout1.addStretch(1)
        layout1.addWidget(self.btn2)

        layout.addLayout(layout1)
        layout.addWidget(self.btn1)
        self.setLayout(layout)
        self.btn1.clicked.connect(self.click1)
        self.btn2.clicked.connect(self.click2)



    def click1(self):
        win32gui.SetForegroundWindow(windowsL[0][self.cb.currentIndex()])
        v=self.text1.toPlainText()
        if self.c.isChecked():
            for i in v.split('\n'):
                for i2 in i:
                    pyautogui.write(i2)
                    sleep(0.1)
                pyautogui.press('enter')
                sleep(1)
        else:
            for i in v.split('\n'):
                pyautogui.write(i)
                sleep(0.1)
                pyautogui.press('enter')
                sleep(0.1)

    def click2(self):
        self.cb.clear()
        windowsList()
        self.cb.addItems(windowsL[1])



windowsList()
app = QApplication(sys.argv)
form = Win()
form.show()
sys.exit(app.exec_())

